import {FC,useState,useEffect,useMemo } from 'react';
import { Layout, Menu,MenuProps } from 'antd';
import "./index.css"
// 引入routes
import routes from "@/router/routes"
import { useNavigate } from 'react-router-dom';

const { Sider } = Layout;

// 声明类型
type Iprops = {
    collapsed:boolean
}

// 将主页的所有子页面 用作菜单数据
let target = routes.find(item => item.path === '/')

// 创建一个方法 递归生产menu
// antd中自带的menu类型
type MenuItem = Required<MenuProps>['items'][number] & {children?:MenuItem[]};



//递归将routes处理成Menu中items那种数据结构 {key:"xx",label:"xxx",icon:"xxx",children:"xx"}
let createMenu = (routes:Array<RouteObj>):MenuItem[] => {
    let menulist: Array<MenuItem> = []
    
    routes.length && routes.forEach((route) => {
    

        // 声明处理之后的对象
        let obj:MenuItem = {
            label:route.label,
            key:route.key,
            icon:route.icon
        }
        
        //如果当前的route有子节点,并且子节点的长度大于0,那么就给obj添加一个children属性,递归函数,将children传入,重新生成一份符合Menu的ItemType配置的数据
        route.children && route.children.length > 0 && (obj.children = createMenu(route.children))
        //将处理好的数据,添加到menulist里面
        menulist.push(obj)
    })
    return menulist
}


const SiderBase:FC<Iprops> = (props) => {

    let navigate = useNavigate()
    let {collapsed} = props
    // 一个用于存储展开菜单key的数组
    let [openKey,setOpenKey] = useState<string[]>([])
    // 缓存收起之前的展开状态
    let [cacheOpenKey,setCacheOpenKey] = useState<string[]>([])

    //将路由配置中,路径=="/"的路由配置的children,传入到这个函数中,进行数据处理
    let routesChildren = useMemo(() => {
        return routes.find(route => route.path === "/")!.children
    }, [routes])

    //计算出符合菜单配置的数据
    let menulist = createMenu(routesChildren!);

    // 菜单的点击事件
    let handleClick = (item:any) => {
        // console.log(item)
        let path = '/' + item.keyPath.reverse().join('/')
        navigate(path)
    }

    // 菜单展开是触发的事件
    let handleOpenChange = (item:string[]) => {
        // console.log(item)
        setOpenKey(item)
    }

    // 解决菜单闪烁问题
    useEffect(()=>{
        if(collapsed){
            // 菜单折叠起来了
            // 收起所有子菜单
            setCacheOpenKey([...openKey])
            setOpenKey([])
        }else{
            setOpenKey([...cacheOpenKey])
        }
    },[collapsed])

    return (
        <Sider className='sider' trigger={null} collapsible collapsed={collapsed}>
            <div className="logo" />
            <Menu
                theme="dark"
                mode="inline"
                defaultSelectedKeys={['1']}
                items={menulist}
                onClick={handleClick}
                onOpenChange={handleOpenChange}
                openKeys={openKey}
            />
        </Sider>
    )
}


export default SiderBase